<template>
  <div 
    class="knowledge-card bg-white rounded-lg shadow-md border border-gray-200 absolute overflow-hidden"
    :style="{ width: width + 'px', height: height + 'px', left: posX + 'px', top: posY + 'px' }"
    ref="cardElement"
  >
    <!-- 标题栏 -->
    <div class="bg-gray-100 px-4 py-3 flex justify-between items-center border-b border-gray-200 cursor-move" @mousedown="startDrag">
      <div class="font-medium text-gray-700">知识卡片</div>
      <button @click="$emit('close')" class="text-gray-500 hover:text-gray-700 focus:outline-none">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
          <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
        </svg>
      </button>
    </div>
    
    <!-- 内容区域 - 可滚动 -->
    <div class="content-area p-4 overflow-y-auto h-[calc(100%-58px)]" v-html="sanitizedHtml"></div>
    
    <!-- 拖动区域 - 底部边缘 -->
    <div 
      class="resize-handle w-6 h-6 absolute bottom-0 right-0 cursor-se-resize flex items-center justify-center text-gray-400"
      ref="resizeHandle"
    >
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="15 3 21 3 21 9"></polyline>
        <polyline points="9 21 3 21 3 15"></polyline>
        <line x1="21" y1="3" x2="14" y2="10"></line>
        <line x1="3" y1="21" x2="10" y2="14"></line>
      </svg>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import DOMPurify from 'dompurify';

// 接收HTML内容作为props
const props = defineProps({
  htmlContent: {
    type: String,
    default: ''
  },
  initialX: {
    type: Number,
    default: null
  },
  initialY: {
    type: Number,
    default: null
  }
});

// 定义事件
const emit = defineEmits(['close']);

// 使用DOMPurify清洗HTML内容
const sanitizedHtml = computed(() => {
  // return DOMPurify.sanitize(props.htmlContent);
  return props.htmlContent;
});

// 卡片位置和大小状态
const posX = ref(0);
const posY = ref(0);
const width = ref(600); // 增加默认宽度
const height = ref(500); // 增加默认高度
const cardElement = ref(null);
const resizeHandle = ref(null);

// 拖动相关变量
let isDragging = false;
let dragStartX = 0;
let dragStartY = 0;
let initialPosX = 0;
let initialPosY = 0;

// 缩放相关变量
let isResizing = false;
let resizeStartX = 0;
let resizeStartY = 0;
let initialWidth = 0;
let initialHeight = 0;

// 计算窗口中央位置
function calculateCenterPosition() {
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;
  
  return {
    x: (windowWidth - width.value) / 2,
    y: (windowHeight - height.value) / 2
  };
}

// 拖动处理函数
function startDrag(e) {
  // 如果点击的是缩放手柄或关闭按钮，不进行拖动
  if (e.target === resizeHandle.value || resizeHandle.value.contains(e.target) || 
      e.target.closest('button')) {
    return;
  }
  
  isDragging = true;
  dragStartX = e.clientX;
  dragStartY = e.clientY;
  initialPosX = posX.value;
  initialPosY = posY.value;
  
  // 防止文本选择
  e.preventDefault();
}

function doDrag(e) {
  if (!isDragging) return;
  
  const dx = e.clientX - dragStartX;
  const dy = e.clientY - dragStartY;
  
  posX.value = initialPosX + dx;
  posY.value = initialPosY + dy;
}

function endDrag() {
  isDragging = false;
}

// 缩放处理函数
function startResize(e) {
  isResizing = true;
  resizeStartX = e.clientX;
  resizeStartY = e.clientY;
  initialWidth = width.value;
  initialHeight = height.value;
  
  // 防止文本选择
  e.preventDefault();
}

function doResize(e) {
  if (!isResizing) return;
  
  const dx = e.clientX - resizeStartX;
  const dy = e.clientY - resizeStartY;
  
  // 设置最小尺寸
  width.value = Math.max(300, initialWidth + dx);
  height.value = Math.max(200, initialHeight + dy);
}

function endResize() {
  isResizing = false;
}

// 组件挂载和卸载时设置事件监听
onMounted(() => {
  // 设置初始位置，优先使用传入的位置，否则居中显示
  const centerPos = calculateCenterPosition();
  posX.value = props.initialX !== null ? props.initialX : centerPos.x;
  posY.value = props.initialY !== null ? props.initialY : centerPos.y;
  
  // 拖动事件监听
  if (cardElement.value) {
    cardElement.value.addEventListener('mousedown', startDrag);
  }
  
  // 缩放事件监听
  if (resizeHandle.value) {
    resizeHandle.value.addEventListener('mousedown', startResize);
  }
  
  // 全局事件监听
  window.addEventListener('mousemove', (e) => {
    doDrag(e);
    doResize(e);
  });
  
  window.addEventListener('mouseup', () => {
    endDrag();
    endResize();
  });
});

// 窗口大小改变时重新居中
const handleResize = () => {
  const centerPos = calculateCenterPosition();
  // 只有在组件刚刚创建时才自动居中
  const initialCenterPos = calculateCenterPosition();
  if (Math.abs(posX.value - initialCenterPos.x) < 10 && 
      Math.abs(posY.value - initialCenterPos.y) < 10) {
    posX.value = centerPos.x;
    posY.value = centerPos.y;
  }
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  // 清理事件监听
  if (cardElement.value) {
    cardElement.value.removeEventListener('mousedown', startDrag);
  }
  
  if (resizeHandle.value) {
    resizeHandle.value.removeEventListener('mousedown', startResize);
  }
  
  window.removeEventListener('mousemove', doDrag);
  window.removeEventListener('mousemove', doResize);
  window.removeEventListener('mouseup', endDrag);
  window.removeEventListener('mouseup', endResize);
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.knowledge-card {
  user-select: none;
  z-index: 50;
}

.content-area {
  user-select: text;
}

.content-area :deep(*) {
  max-width: 100%;
}
</style>
